package com.project.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.project.bean.BuyCarBean;
import com.project.bean.ProductBean;
import com.project.mapper.IBuyCarMapper;
import com.project.mapper.IProductMapper;
import com.project.service.IBuyCarService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
@Transactional
public class BuyCarServiceImpl implements IBuyCarService {
    @Autowired
    private IBuyCarMapper buyCarMapper;
    @Autowired
    private IProductMapper productMapper;
    @Override
    public void add(ProductBean product, Integer buyNum, Integer userId, String operate) {
        if ("update".equals(operate)){
            QueryWrapper<BuyCarBean> qw = new QueryWrapper<>();
            qw.eq("fk_userId",userId);
            qw.eq("fk_productId",product.getProductId());
            BuyCarBean buyCarBean=buyCarMapper.selectOne(qw);
            if (buyCarBean==null){
                //不存在就加
                buyCarMapper.insert(new BuyCarBean(buyNum,product.getProductId(),userId));
            }else {
                //存在，加数字
                buyCarBean.setNum(buyCarBean.getNum()+buyNum);
                buyCarMapper.updateById(buyCarBean);
            }
        }else if("add".equals(operate)){
            //添加商品
            productMapper.insert(product);
            //添加购物车
            buyCarMapper.insert(new BuyCarBean(buyNum,product.getProductId(),userId));
        }
    }

    @Override
    public void del(Integer buyCatId) {
        buyCarMapper.deleteById(buyCatId);
    }

    @Override
    public List<BuyCarBean> findAll(Integer userId) {
        return buyCarMapper.findAll(userId);
    }
    @Override
    public void updatePrice(Integer buyCatId, Integer price) {
        BuyCarBean buyCar = buyCarMapper.selectById(buyCatId);
        buyCar.setPrice(price);
        buyCarMapper.updateById(buyCar);
    }

    @Override
    public void updateNum(Integer buyCatId, Integer num) {
        BuyCarBean buyCar = buyCarMapper.selectById(buyCatId);
        buyCar.setNum(num);
        buyCarMapper.updateById(buyCar);
    }

}
